import React, { useState } from 'react';
import { Database, Save, RotateCcw, TestTube, Eye, EyeOff, AlertCircle, CheckCircle, Loader2 } from 'lucide-react';
import MenuToggle from '../components/MenuToggle';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';

const DatabaseConfig = ({ toggleSidebar }) => {
  const [showPasswords, setShowPasswords] = useState({});
  const [testingConnection, setTestingConnection] = useState({});
  const [connectionStatus, setConnectionStatus] = useState({});

  // 主数据库配置
  const [primaryConfig, setPrimaryConfig] = useState({
    type: 'mysql',
    host: 'localhost',
    port: 3306,
    database: 'cloud_system',
    username: 'root',
    password: 'password123',
    charset: 'utf8mb4',
    timezone: '+08:00',
    maxConnections: 100,
    connectionTimeout: 30000,
    enableSSL: false,
    sslCert: '',
    sslKey: '',
    sslCA: ''
  });

  // 读库配置
  const [readConfig, setReadConfig] = useState({
    enabled: true,
    type: 'mysql',
    host: 'read.localhost',
    port: 3306,
    database: 'cloud_system',
    username: 'readonly',
    password: 'readonly123',
    charset: 'utf8mb4',
    timezone: '+08:00',
    maxConnections: 50,
    connectionTimeout: 30000,
    enableSSL: false
  });

  // Redis配置
  const [redisConfig, setRedisConfig] = useState({
    host: 'localhost',
    port: 6379,
    password: '',
    database: 0,
    maxConnections: 20,
    connectionTimeout: 5000,
    enableCluster: false,
    clusterNodes: '',
    keyPrefix: 'cloud:',
    defaultTTL: 3600
  });

  // MongoDB配置
  const [mongoConfig, setMongoConfig] = useState({
    enabled: false,
    host: 'localhost',
    port: 27017,
    database: 'cloud_logs',
    username: 'mongo_user',
    password: 'mongo_pass',
    authDatabase: 'admin',
    maxConnections: 10,
    connectionTimeout: 10000,
    enableSSL: false
  });

  const databaseTypes = [
    { value: 'mysql', label: 'MySQL' },
    { value: 'postgresql', label: 'PostgreSQL' },
    { value: 'sqlite', label: 'SQLite' },
    { value: 'sqlserver', label: 'SQL Server' },
    { value: 'oracle', label: 'Oracle' }
  ];

  const charsets = [
    { value: 'utf8mb4', label: 'UTF8MB4' },
    { value: 'utf8', label: 'UTF8' },
    { value: 'latin1', label: 'Latin1' },
    { value: 'gbk', label: 'GBK' }
  ];

  const timezones = [
    { value: '+08:00', label: '北京时间 (+08:00)' },
    { value: '+00:00', label: 'UTC (+00:00)' },
    { value: '+09:00', label: '东京时间 (+09:00)' },
    { value: '-05:00', label: '纽约时间 (-05:00)' }
  ];

  const togglePasswordVisibility = (configType) => {
    setShowPasswords(prev => ({
      ...prev,
      [configType]: !prev[configType]
    }));
  };

  const testConnection = async (configType) => {
    setTestingConnection(prev => ({ ...prev, [configType]: true }));
    
    // 模拟连接测试
    setTimeout(() => {
      const isSuccess = Math.random() > 0.3; // 70% 成功率
      setConnectionStatus(prev => ({
        ...prev,
        [configType]: isSuccess ? 'success' : 'error'
      }));
      setTestingConnection(prev => ({ ...prev, [configType]: false }));
    }, 2000);
  };

  const handleSave = () => {
    const allConfig = {
      primary: primaryConfig,
      read: readConfig,
      redis: redisConfig,
      mongodb: mongoConfig
    };
    
    console.log('保存数据库配置:', allConfig);
    alert('数据库配置已保存');
  };

  const handleReset = () => {
    if (confirm('确定要重置所有数据库配置到默认值吗？')) {
      setPrimaryConfig({
        type: 'mysql',
        host: 'localhost',
        port: 3306,
        database: 'cloud_system',
        username: 'root',
        password: 'password123',
        charset: 'utf8mb4',
        timezone: '+08:00',
        maxConnections: 100,
        connectionTimeout: 30000,
        enableSSL: false,
        sslCert: '',
        sslKey: '',
        sslCA: ''
      });
      
      setReadConfig({
        enabled: true,
        type: 'mysql',
        host: 'read.localhost',
        port: 3306,
        database: 'cloud_system',
        username: 'readonly',
        password: 'readonly123',
        charset: 'utf8mb4',
        timezone: '+08:00',
        maxConnections: 50,
        connectionTimeout: 30000,
        enableSSL: false
      });
      
      setRedisConfig({
        host: 'localhost',
        port: 6379,
        password: '',
        database: 0,
        maxConnections: 20,
        connectionTimeout: 5000,
        enableCluster: false,
        clusterNodes: '',
        keyPrefix: 'cloud:',
        defaultTTL: 3600
      });
      
      setMongoConfig({
        enabled: false,
        host: 'localhost',
        port: 27017,
        database: 'cloud_logs',
        username: 'mongo_user',
        password: 'mongo_pass',
        authDatabase: 'admin',
        maxConnections: 10,
        connectionTimeout: 10000,
        enableSSL: false
      });
      
      setConnectionStatus({});
    }
  };

  const getConnectionStatusBadge = (configType) => {
    const status = connectionStatus[configType];
    const testing = testingConnection[configType];
    
    if (testing) {
      return (
        <Badge className="bg-blue-100 text-blue-800">
          <Loader2 className="w-3 h-3 mr-1 animate-spin" />
          测试中
        </Badge>
      );
    }
    
    if (status === 'success') {
      return (
        <Badge className="bg-green-100 text-green-800">
          <CheckCircle className="w-3 h-3 mr-1" />
          连接成功
        </Badge>
      );
    }
    
    if (status === 'error') {
      return (
        <Badge className="bg-red-100 text-red-800">
          <AlertCircle className="w-3 h-3 mr-1" />
          连接失败
        </Badge>
      );
    }
    
    return null;
  };

  return (
    <>
      {/* 头部工具栏 */}
      <div className="mt-3">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：菜单按钮和标题 */}
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-green-500 to-green-600 rounded-xl flex items-center justify-center">
                  <Database className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    数据库配置
                  </h1>
                  <p className="text-sm text-material-grey-600">
                    管理数据库连接和参数设置
                  </p>
                </div>
              </div>
            </div>

            {/* 右侧：操作按钮 */}
            <div className="flex items-center space-x-3">
              <Button variant="outline" onClick={handleReset}>
                <RotateCcw className="w-4 h-4 mr-2" />
                重置配置
              </Button>
              <Button onClick={handleSave} className="bg-primary hover:bg-primary-600">
                <Save className="w-4 h-4 mr-2" />
                保存配置
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 container mx-auto px-4 py-6">
        <Tabs defaultValue="primary" className="w-full">
          <TabsList className="grid w-full grid-cols-4">
            <TabsTrigger value="primary">主数据库</TabsTrigger>
            <TabsTrigger value="read">读库配置</TabsTrigger>
            <TabsTrigger value="redis">Redis缓存</TabsTrigger>
            <TabsTrigger value="mongodb">MongoDB</TabsTrigger>
          </TabsList>

          {/* 主数据库配置 */}
          <TabsContent value="primary" className="mt-6">
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle className="flex items-center space-x-2">
                    <Database className="w-5 h-5" />
                    <span>主数据库配置</span>
                  </CardTitle>
                  <div className="flex items-center space-x-2">
                    {getConnectionStatusBadge('primary')}
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => testConnection('primary')}
                      disabled={testingConnection.primary}
                    >
                      <TestTube className="w-4 h-4 mr-2" />
                      测试连接
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <Label htmlFor="primary-type">数据库类型</Label>
                    <Select value={primaryConfig.type} onValueChange={(value) => setPrimaryConfig(prev => ({ ...prev, type: value }))}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {databaseTypes.map(type => (
                          <SelectItem key={type.value} value={type.value}>
                            {type.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  
                  <div>
                    <Label htmlFor="primary-host">主机地址</Label>
                    <Input
                      id="primary-host"
                      value={primaryConfig.host}
                      onChange={(e) => setPrimaryConfig(prev => ({ ...prev, host: e.target.value }))}
                      placeholder="localhost"
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="primary-port">端口</Label>
                    <Input
                      id="primary-port"
                      type="number"
                      value={primaryConfig.port}
                      onChange={(e) => setPrimaryConfig(prev => ({ ...prev, port: parseInt(e.target.value) || 3306 }))}
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="primary-database">数据库名</Label>
                    <Input
                      id="primary-database"
                      value={primaryConfig.database}
                      onChange={(e) => setPrimaryConfig(prev => ({ ...prev, database: e.target.value }))}
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="primary-username">用户名</Label>
                    <Input
                      id="primary-username"
                      value={primaryConfig.username}
                      onChange={(e) => setPrimaryConfig(prev => ({ ...prev, username: e.target.value }))}
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="primary-password">密码</Label>
                    <div className="relative">
                      <Input
                        id="primary-password"
                        type={showPasswords.primary ? 'text' : 'password'}
                        value={primaryConfig.password}
                        onChange={(e) => setPrimaryConfig(prev => ({ ...prev, password: e.target.value }))}
                      />
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="absolute right-0 top-0 h-full px-3"
                        onClick={() => togglePasswordVisibility('primary')}
                      >
                        {showPasswords.primary ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                      </Button>
                    </div>
                  </div>
                  
                  <div>
                    <Label htmlFor="primary-charset">字符集</Label>
                    <Select value={primaryConfig.charset} onValueChange={(value) => setPrimaryConfig(prev => ({ ...prev, charset: value }))}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {charsets.map(charset => (
                          <SelectItem key={charset.value} value={charset.value}>
                            {charset.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  
                  <div>
                    <Label htmlFor="primary-timezone">时区</Label>
                    <Select value={primaryConfig.timezone} onValueChange={(value) => setPrimaryConfig(prev => ({ ...prev, timezone: value }))}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {timezones.map(tz => (
                          <SelectItem key={tz.value} value={tz.value}>
                            {tz.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  
                  <div>
                    <Label htmlFor="primary-maxConnections">最大连接数</Label>
                    <Input
                      id="primary-maxConnections"
                      type="number"
                      value={primaryConfig.maxConnections}
                      onChange={(e) => setPrimaryConfig(prev => ({ ...prev, maxConnections: parseInt(e.target.value) || 100 }))}
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="primary-timeout">连接超时 (毫秒)</Label>
                    <Input
                      id="primary-timeout"
                      type="number"
                      value={primaryConfig.connectionTimeout}
                      onChange={(e) => setPrimaryConfig(prev => ({ ...prev, connectionTimeout: parseInt(e.target.value) || 30000 }))}
                    />
                  </div>
                </div>
                
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <Label htmlFor="primary-ssl">启用SSL</Label>
                      <p className="text-sm text-material-grey-600">使用SSL加密数据库连接</p>
                    </div>
                    <Switch
                      id="primary-ssl"
                      checked={primaryConfig.enableSSL}
                      onCheckedChange={(checked) => setPrimaryConfig(prev => ({ ...prev, enableSSL: checked }))}
                    />
                  </div>
                  
                  {primaryConfig.enableSSL && (
                    <div className="grid grid-cols-1 gap-4 ml-6">
                      <div>
                        <Label htmlFor="primary-sslCert">SSL证书路径</Label>
                        <Input
                          id="primary-sslCert"
                          value={primaryConfig.sslCert}
                          onChange={(e) => setPrimaryConfig(prev => ({ ...prev, sslCert: e.target.value }))}
                          placeholder="/path/to/cert.pem"
                        />
                      </div>
                      <div>
                        <Label htmlFor="primary-sslKey">SSL私钥路径</Label>
                        <Input
                          id="primary-sslKey"
                          value={primaryConfig.sslKey}
                          onChange={(e) => setPrimaryConfig(prev => ({ ...prev, sslKey: e.target.value }))}
                          placeholder="/path/to/key.pem"
                        />
                      </div>
                      <div>
                        <Label htmlFor="primary-sslCA">SSL CA证书路径</Label>
                        <Input
                          id="primary-sslCA"
                          value={primaryConfig.sslCA}
                          onChange={(e) => setPrimaryConfig(prev => ({ ...prev, sslCA: e.target.value }))}
                          placeholder="/path/to/ca.pem"
                        />
                      </div>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* 读库配置 */}
          <TabsContent value="read" className="mt-6">
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle className="flex items-center space-x-2">
                    <Database className="w-5 h-5" />
                    <span>读库配置</span>
                  </CardTitle>
                  <div className="flex items-center space-x-2">
                    {getConnectionStatusBadge('read')}
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => testConnection('read')}
                      disabled={testingConnection.read || !readConfig.enabled}
                    >
                      <TestTube className="w-4 h-4 mr-2" />
                      测试连接
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="flex items-center justify-between">
                  <div>
                    <Label htmlFor="read-enabled">启用读写分离</Label>
                    <p className="text-sm text-material-grey-600">配置独立的读库以提高性能</p>
                  </div>
                  <Switch
                    id="read-enabled"
                    checked={readConfig.enabled}
                    onCheckedChange={(checked) => setReadConfig(prev => ({ ...prev, enabled: checked }))}
                  />
                </div>
                
                {readConfig.enabled && (
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                      <Label htmlFor="read-type">数据库类型</Label>
                      <Select value={readConfig.type} onValueChange={(value) => setReadConfig(prev => ({ ...prev, type: value }))}>
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          {databaseTypes.map(type => (
                            <SelectItem key={type.value} value={type.value}>
                              {type.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    
                    <div>
                      <Label htmlFor="read-host">主机地址</Label>
                      <Input
                        id="read-host"
                        value={readConfig.host}
                        onChange={(e) => setReadConfig(prev => ({ ...prev, host: e.target.value }))}
                      />
                    </div>
                    
                    <div>
                      <Label htmlFor="read-port">端口</Label>
                      <Input
                        id="read-port"
                        type="number"
                        value={readConfig.port}
                        onChange={(e) => setReadConfig(prev => ({ ...prev, port: parseInt(e.target.value) || 3306 }))}
                      />
                    </div>
                    
                    <div>
                      <Label htmlFor="read-database">数据库名</Label>
                      <Input
                        id="read-database"
                        value={readConfig.database}
                        onChange={(e) => setReadConfig(prev => ({ ...prev, database: e.target.value }))}
                      />
                    </div>
                    
                    <div>
                      <Label htmlFor="read-username">用户名</Label>
                      <Input
                        id="read-username"
                        value={readConfig.username}
                        onChange={(e) => setReadConfig(prev => ({ ...prev, username: e.target.value }))}
                      />
                    </div>
                    
                    <div>
                      <Label htmlFor="read-password">密码</Label>
                      <div className="relative">
                        <Input
                          id="read-password"
                          type={showPasswords.read ? 'text' : 'password'}
                          value={readConfig.password}
                          onChange={(e) => setReadConfig(prev => ({ ...prev, password: e.target.value }))}
                        />
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          className="absolute right-0 top-0 h-full px-3"
                          onClick={() => togglePasswordVisibility('read')}
                        >
                          {showPasswords.read ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                        </Button>
                      </div>
                    </div>
                    
                    <div>
                      <Label htmlFor="read-maxConnections">最大连接数</Label>
                      <Input
                        id="read-maxConnections"
                        type="number"
                        value={readConfig.maxConnections}
                        onChange={(e) => setReadConfig(prev => ({ ...prev, maxConnections: parseInt(e.target.value) || 50 }))}
                      />
                    </div>
                    
                    <div>
                      <Label htmlFor="read-timeout">连接超时 (毫秒)</Label>
                      <Input
                        id="read-timeout"
                        type="number"
                        value={readConfig.connectionTimeout}
                        onChange={(e) => setReadConfig(prev => ({ ...prev, connectionTimeout: parseInt(e.target.value) || 30000 }))}
                      />
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          {/* Redis配置 */}
          <TabsContent value="redis" className="mt-6">
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle className="flex items-center space-x-2">
                    <Database className="w-5 h-5" />
                    <span>Redis缓存配置</span>
                  </CardTitle>
                  <div className="flex items-center space-x-2">
                    {getConnectionStatusBadge('redis')}
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => testConnection('redis')}
                      disabled={testingConnection.redis}
                    >
                      <TestTube className="w-4 h-4 mr-2" />
                      测试连接
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <Label htmlFor="redis-host">主机地址</Label>
                    <Input
                      id="redis-host"
                      value={redisConfig.host}
                      onChange={(e) => setRedisConfig(prev => ({ ...prev, host: e.target.value }))}
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="redis-port">端口</Label>
                    <Input
                      id="redis-port"
                      type="number"
                      value={redisConfig.port}
                      onChange={(e) => setRedisConfig(prev => ({ ...prev, port: parseInt(e.target.value) || 6379 }))}
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="redis-password">密码 (可选)</Label>
                    <div className="relative">
                      <Input
                        id="redis-password"
                        type={showPasswords.redis ? 'text' : 'password'}
                        value={redisConfig.password}
                        onChange={(e) => setRedisConfig(prev => ({ ...prev, password: e.target.value }))}
                        placeholder="留空表示无密码"
                      />
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="absolute right-0 top-0 h-full px-3"
                        onClick={() => togglePasswordVisibility('redis')}
                      >
                        {showPasswords.redis ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                      </Button>
                    </div>
                  </div>
                  
                  <div>
                    <Label htmlFor="redis-database">数据库索引</Label>
                    <Input
                      id="redis-database"
                      type="number"
                      min="0"
                      max="15"
                      value={redisConfig.database}
                      onChange={(e) => setRedisConfig(prev => ({ ...prev, database: parseInt(e.target.value) || 0 }))}
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="redis-maxConnections">最大连接数</Label>
                    <Input
                      id="redis-maxConnections"
                      type="number"
                      value={redisConfig.maxConnections}
                      onChange={(e) => setRedisConfig(prev => ({ ...prev, maxConnections: parseInt(e.target.value) || 20 }))}
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="redis-timeout">连接超时 (毫秒)</Label>
                    <Input
                      id="redis-timeout"
                      type="number"
                      value={redisConfig.connectionTimeout}
                      onChange={(e) => setRedisConfig(prev => ({ ...prev, connectionTimeout: parseInt(e.target.value) || 5000 }))}
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="redis-keyPrefix">键前缀</Label>
                    <Input
                      id="redis-keyPrefix"
                      value={redisConfig.keyPrefix}
                      onChange={(e) => setRedisConfig(prev => ({ ...prev, keyPrefix: e.target.value }))}
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="redis-defaultTTL">默认TTL (秒)</Label>
                    <Input
                      id="redis-defaultTTL"
                      type="number"
                      value={redisConfig.defaultTTL}
                      onChange={(e) => setRedisConfig(prev => ({ ...prev, defaultTTL: parseInt(e.target.value) || 3600 }))}
                    />
                  </div>
                </div>
                
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <Label htmlFor="redis-cluster">启用集群模式</Label>
                      <p className="text-sm text-material-grey-600">使用Redis集群提高可用性</p>
                    </div>
                    <Switch
                      id="redis-cluster"
                      checked={redisConfig.enableCluster}
                      onCheckedChange={(checked) => setRedisConfig(prev => ({ ...prev, enableCluster: checked }))}
                    />
                  </div>
                  
                  {redisConfig.enableCluster && (
                    <div>
                      <Label htmlFor="redis-clusterNodes">集群节点</Label>
                      <Input
                        id="redis-clusterNodes"
                        value={redisConfig.clusterNodes}
                        onChange={(e) => setRedisConfig(prev => ({ ...prev, clusterNodes: e.target.value }))}
                        placeholder="host1:port1,host2:port2,host3:port3"
                      />
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* MongoDB配置 */}
          <TabsContent value="mongodb" className="mt-6">
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle className="flex items-center space-x-2">
                    <Database className="w-5 h-5" />
                    <span>MongoDB配置</span>
                  </CardTitle>
                  <div className="flex items-center space-x-2">
                    {getConnectionStatusBadge('mongodb')}
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => testConnection('mongodb')}
                      disabled={testingConnection.mongodb || !mongoConfig.enabled}
                    >
                      <TestTube className="w-4 h-4 mr-2" />
                      测试连接
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="flex items-center justify-between">
                  <div>
                    <Label htmlFor="mongo-enabled">启用MongoDB</Label>
                    <p className="text-sm text-material-grey-600">用于存储日志和文档数据</p>
                  </div>
                  <Switch
                    id="mongo-enabled"
                    checked={mongoConfig.enabled}
                    onCheckedChange={(checked) => setMongoConfig(prev => ({ ...prev, enabled: checked }))}
                  />
                </div>
                
                {mongoConfig.enabled && (
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                      <Label htmlFor="mongo-host">主机地址</Label>
                      <Input
                        id="mongo-host"
                        value={mongoConfig.host}
                        onChange={(e) => setMongoConfig(prev => ({ ...prev, host: e.target.value }))}
                      />
                    </div>
                    
                    <div>
                      <Label htmlFor="mongo-port">端口</Label>
                      <Input
                        id="mongo-port"
                        type="number"
                        value={mongoConfig.port}
                        onChange={(e) => setMongoConfig(prev => ({ ...prev, port: parseInt(e.target.value) || 27017 }))}
                      />
                    </div>
                    
                    <div>
                      <Label htmlFor="mongo-database">数据库名</Label>
                      <Input
                        id="mongo-database"
                        value={mongoConfig.database}
                        onChange={(e) => setMongoConfig(prev => ({ ...prev, database: e.target.value }))}
                      />
                    </div>
                    
                    <div>
                      <Label htmlFor="mongo-authDatabase">认证数据库</Label>
                      <Input
                        id="mongo-authDatabase"
                        value={mongoConfig.authDatabase}
                        onChange={(e) => setMongoConfig(prev => ({ ...prev, authDatabase: e.target.value }))}
                      />
                    </div>
                    
                    <div>
                      <Label htmlFor="mongo-username">用户名</Label>
                      <Input
                        id="mongo-username"
                        value={mongoConfig.username}
                        onChange={(e) => setMongoConfig(prev => ({ ...prev, username: e.target.value }))}
                      />
                    </div>
                    
                    <div>
                      <Label htmlFor="mongo-password">密码</Label>
                      <div className="relative">
                        <Input
                          id="mongo-password"
                          type={showPasswords.mongodb ? 'text' : 'password'}
                          value={mongoConfig.password}
                          onChange={(e) => setMongoConfig(prev => ({ ...prev, password: e.target.value }))}
                        />
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          className="absolute right-0 top-0 h-full px-3"
                          onClick={() => togglePasswordVisibility('mongodb')}
                        >
                          {showPasswords.mongodb ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                        </Button>
                      </div>
                    </div>
                    
                    <div>
                      <Label htmlFor="mongo-maxConnections">最大连接数</Label>
                      <Input
                        id="mongo-maxConnections"
                        type="number"
                        value={mongoConfig.maxConnections}
                        onChange={(e) => setMongoConfig(prev => ({ ...prev, maxConnections: parseInt(e.target.value) || 10 }))}
                      />
                    </div>
                    
                    <div>
                      <Label htmlFor="mongo-timeout">连接超时 (毫秒)</Label>
                      <Input
                        id="mongo-timeout"
                        type="number"
                        value={mongoConfig.connectionTimeout}
                        onChange={(e) => setMongoConfig(prev => ({ ...prev, connectionTimeout: parseInt(e.target.value) || 10000 }))}
                      />
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    </>
  );
};

export default DatabaseConfig;
